/**
 * 
 */
package com.expense.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * @author Administrator
 * 
 */
public class MailUtil {
	
	/**
	 * 发送邮件
	 * */
	public static boolean sendMail(MailBean mailBean) {
		boolean iflag = true;
		try {
			Properties props = new Properties();
			props.put("mail.smtp.host", mailBean.getHostName());
			props.put("mail.smtp.auth", "true");
			final String usernameFin = mailBean.getUsername();
			final String passwordFin = mailBean.getPassword();
			Session session = Session.getDefaultInstance(props,
					new Authenticator() {
						public PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(usernameFin,
									passwordFin);
						}
					});
			// session.setDebug(true);

			MimeMessage message = new MimeMessage(session);
			// 给消息对象设置发件人/收件人/主题/发信时间
			InternetAddress from = new InternetAddress(mailBean.getUsername());
			message.setFrom(from);

			// 发送
			if (mailBean.getTosUser() != null) {
				Address[] addresses = new Address[mailBean.getTosUser().length];
				InternetAddress addre = null;
				for (int i = 0; i < mailBean.getTosUser().length; i++) {
					addre = new InternetAddress(mailBean.getTosUser()[i]);
					addresses[i] = addre;
				}
				message.setRecipients(Message.RecipientType.TO, addresses);
			}
			// 抄送
			if (mailBean.getCcsUser() != null) {
				Address[] addresses = new Address[mailBean.getCcsUser().length];
				InternetAddress addre = null;
				for (int i = 0; i < mailBean.getCcsUser().length; i++) {
					addre = new InternetAddress(mailBean.getCcsUser()[i]);
					addresses[i] = addre;
				}
				message.setRecipients(Message.RecipientType.CC, addresses);
			}
			// 暗送
			if (mailBean.getBccsUser() != null) {
				Address[] addresses = new Address[mailBean.getBccsUser().length];
				InternetAddress addre = null;
				for (int i = 0; i < mailBean.getBccsUser().length; i++) {
					addre = new InternetAddress(mailBean.getBccsUser()[i]);
					addresses[i] = addre;
				}
				message.setRecipients(Message.RecipientType.BCC, addresses);
			}

			message.setSubject(mailBean.getTitle());
			message.setSentDate(new Date());

			Multipart multipart = new MimeMultipart();// 新建一个MimeMultipart对象用来存放多个BodyPart对象
			// 设置信件文本内容
			BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
			mdp.setContent(mailBean.getContent(), "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式
			multipart.addBodyPart(mdp);// 将含有信件内容的BodyPart加入到MimeMultipart对象中

			// 设置附件
			if (mailBean.getFiles() != null) {
				File file = null;
				for (int i = 0; i < mailBean.getFiles().size(); i++) {
					file = (File) mailBean.getFiles().get(i);
					MimeBodyPart mbpFile = new MimeBodyPart();
					FileDataSource fileDataSource = new FileDataSource(file);
					mbpFile.setDataHandler(new DataHandler(fileDataSource));
					mbpFile.setFileName(fileDataSource.getName());
					// 向MimeMessage添加（Multipart代表附件）
					multipart.addBodyPart(mbpFile);
				}
			}

			message.setContent(multipart);
			message.saveChanges();

			Transport.send(message);
		} catch (Exception e) {
			// TODO: handle exception
			iflag = false;
			e.printStackTrace();
		}
		return iflag;
	}

	public static void main(String[] args) {
		MailUtil MailUtil=new MailUtil();
		String popServer="pop3.126.com";
		String popUser="xiaojian0819@126.com";
		String popPassword="xj0819";
		
		popServer="pop.qq.com";
		popUser="307041936@qq.com";
		popPassword="xj08190819";
		MailUtil.receive(popServer, popUser, popPassword);
	}
	
	/**
	 * <br>
	 * 方法说明：接收邮件信息 <br>
	 * 输入参数： <br>
	 * 返回类型：
	 */
	public static void receive(String popServer, String popUser,String popPassword) {
		Store store = null;
		Folder folder = null;
		try {
			// 获取默认会话
			Properties props = System.getProperties();
			Session session = Session.getDefaultInstance(props, null);
			// 使用POP3会话机制，连接服务器
			store = session.getStore("pop3");
			store.connect(popServer, popUser, popPassword);
			// 获取默认文件夹
			folder = store.getDefaultFolder();
			if (folder == null)
				throw new Exception("No default folder");
			// 如果是收件箱
			folder = folder.getFolder("INBOX");
			if (folder == null)
				throw new Exception("No POP3 INBOX");
			// 使用只读方式打开收件箱
			folder.open(Folder.READ_ONLY);
			
			// 得到文件夹信息，获取邮件列表
			Message[] msgs = folder.getMessages();
			int messageCount=folder.getMessageCount();//总共数量
			int unreadMessageCount=folder.getUnreadMessageCount();//已读的数量
			int newMessageCount=folder.getNewMessageCount();//未读的数量
			System.out.println("总共数量: " + messageCount );
			System.out.println("已读的数量: " + unreadMessageCount );
			System.out.println("未读的数量: " +newMessageCount );
			
			for (int msgNum = 0; msgNum < msgs.length; msgNum++) {
				if (msgNum<19)  
				printMessage(msgs[msgNum]);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			// 释放资源
			try {
				if (folder != null)
					folder.close(false);
				if (store != null)
					store.close();
			} catch (Exception ex2) {
				ex2.printStackTrace();
			}
		}
	}

	/**
	 * <br>
	 * 方法说明：打印邮件信息 <br>
	 * 输入参数：Message message 信息对象 <br>
	 * 返回类型：
	 */
	public static void printMessage(Message message) {
		try {
			// 获得发送邮件地址
			String from = ((InternetAddress) message.getFrom()[0])
					.getPersonal();
			if (from == null)
				from = ((InternetAddress) message.getFrom()[0]).getAddress();
			System.out.println("FROM: " + from);
			// 获取主题
			String subject = message.getSubject();
			if(from.startsWith("=?GB")||from.startsWith("=?gb")){ 
				System.out.println(MimeUtility.decodeText(subject));
			}else {
				System.out.println("SUBJECT: " + new String(subject.getBytes(),"GBK") );
			}
			
			// 获取信息对象
			Part messagePart = message;
			Object content = messagePart.getContent();
			// 附件
			if (content instanceof Multipart) {
				messagePart = ((Multipart) content).getBodyPart(0);
				System.out.println("[ Multipart Message ]");
			}
			// 获取content类型
			String contentType = messagePart.getContentType();
			// 如果邮件内容是纯文本或者是HTML，那么打印出信息
			System.out.println("CONTENT:" + contentType);
			if (contentType.startsWith("text/plain")
					|| contentType.startsWith("text/html")) {
				InputStream is = messagePart.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is));
				String thisLine = reader.readLine();
				while (thisLine != null) {
					if(from.startsWith("=?GB")||from.startsWith("=?gb")){ 
						System.out.println(MimeUtility.decodeText(thisLine));
					}else {
						if (contentType.toLowerCase().indexOf("utf-8")!=-1) {
							System.out.println(new String(thisLine.getBytes(),"utf-8"));
						}else {
							System.out.println(new String(thisLine.getBytes(),"GBK"));
						}
						
					}
					
					thisLine = reader.readLine();
				}
			}
			System.out.println("-------------- END ---------------");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
